package com.begamer.card.common.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.begamer.card.cache.Cache;
import com.begamer.card.common.Constant;

/**
 * 
 * @ClassName: RequestUtil
 * @Description: TODO request获取参数
 * @author gs
 * @date Nov 10, 2011 3:59:39 PM
 * 
 */
public class RequestUtil {
	private static final Logger logger = Logger.getLogger(RequestUtil.class);

	public static Integer GetParamInteger(HttpServletRequest request,
			String name) {
		return RequestUtil.GetParamInteger(request, name, 0);
	}

	public static Integer GetParamInteger(HttpServletRequest request,
			String name, Integer val) {
		Integer ret = val;

		try {
			ret = new Integer(request.getParameter(name));
		} catch (NumberFormatException e) {
			// logger.warn("GetParamInteger " + name + " Error ! Return Default
			// : " + ret);
		}
		return ret;
	}

	public static Short GetParamShort(HttpServletRequest request, String name) {
		return RequestUtil.GetParamShort(request, name, new Short("0"));
	}

	public static Short GetParamShort(HttpServletRequest request, String name,
			Short val) {
		Short ret = val;

		try {
			ret = new Short(request.getParameter(name));
		} catch (NumberFormatException e) {
			logger.warn("GetParamShort " + name + " Error ! Return Default : "
					+ ret);
		}
		return ret;
	}

	public static String GetParamString(HttpServletRequest request,
			String name, String val) {
		String ret = request.getParameter(name);
		if (ret == null) {
			logger.warn("GetParamString '" + name
					+ "' NULL ! Return Default : " + val);
			return val;
		}
		ret.replace("\"", "&uml;");
		ret.replace("'", "&acute;");
		return ret;
	}

	public static String GetUploadString(
			HashMap<String, FileItem> mapUploadData, String name, String val) {
		if (mapUploadData != null && mapUploadData.containsKey(name)) {
			FileItem item = mapUploadData.get(name);
			if (item.isFormField()) {
				try {
					String ret = item.getString("utf-8");
					ret.replace("\"", "&uml;");
					ret.replace("'", "&acute;");
					return ret;
				} catch (UnsupportedEncodingException e) {
					logger.error("UnsupportedEncodingException - "
							+ e.getMessage(), e);
				}
			}
		}
		logger.warn("GetUploadString '" + name + "' NULL ! Return Default : "
				+ val);
		return val;
	}

	public static Integer GetUploadInteger(
			HashMap<String, FileItem> mapUploadData, String name, Integer val) {
		Integer ret = val;

		try {
			if (val == null)
				ret = new Integer(GetUploadString(mapUploadData, name, null));
			else
				ret = new Integer(GetUploadString(mapUploadData, name, val
						.toString()));
		} catch (NumberFormatException e) {
			logger.warn("GetUploadInteger " + name
					+ " Error ! Return Default : " + ret);
		}

		return ret;
	}

	public static Short GetUploadShort(HashMap<String, FileItem> mapUploadData,
			String name, Short val) {
		Integer def = null;
		if (val != null)
			def = Integer.valueOf(val);

		Integer ret = GetUploadInteger(mapUploadData, name, def);
		if (ret == null)
			return null;

		return ret.shortValue();
	}

	public static FileItem GetUploadFileitem(
			HashMap<String, FileItem> mapUploadData, String name) {
		if (mapUploadData.containsKey(name)) {
			FileItem item = mapUploadData.get(name);

			if (!item.isFormField()) {
				return item;
			}
		}

		logger.warn("GetUploadFileitem '" + name + "' NULL !");
		return null;
	}
	
	/**
	 * 读取流
	 * @param inStream
	 * @return 字节数组
	 * @throws Exception
	 */
	public static byte[] readStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = -1;
		/*while */if ((len = inStream.read(buffer)) != -1) {
			outSteam.write(buffer, 0, len);
		}
		outSteam.close();
		return outSteam.toByteArray();
	}
	
	public static String readParams(HttpServletRequest request)
	{
		InputStream inputStream=null;
		try
		{
			inputStream=request.getInputStream();
			if (inputStream != null) 
			{
				ByteArray ba=new ByteArray();
				byte[] temp=new byte[1024];
				int length=-1;
				while((length=inputStream.read(temp))>0)
				{
					for(int i=0;i<length;i++)
					{
						ba.writeByte(temp[i]);
					}
				}
				return new String(ba.readByteArray(),"UTF-8");
			}
		} 
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			if(inputStream!=null)
			{
				try
				{
					inputStream.close();
				} 
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
		return "";
	}
	
	/**
	 * 设置新密钥
	 * lt@2013-9-5 下午03:32:52
	 * @param request
	 * @return
	 */
	public static String setNewKey(HttpServletRequest request)
	{
		String newKey=EncryptAndDecipher.generateKey();
		//设置新的密钥
		request.getSession().setAttribute(Constant.Key, newKey);
		return newKey;
	}
	
	/**
	 * 检查session是否有密钥
	 * lt@2013-9-5 下午03:33:39
	 * @param request
	 * @return
	 */
	public static ModelAndView check(HttpServletRequest request) throws Exception
	{
		//记录流量
		Cache.recordFlowInfo(2,request.getContentLength());
		String oldKey=(String)request.getSession().getAttribute(Constant.Key);
		if(oldKey==null)
		{
			String newKey=setNewKey(request);
			//设置结果
			setResult(request,newKey);
			return new ModelAndView("/user/result.vm");
		}
		else
		{
			return null;
		}
	}
	
	/**
	 * 获取json信息
	 * lt@2013-9-5 下午03:34:06
	 * @param request
	 * @return
	 */
	public static JSONObject getJsonObject(HttpServletRequest request) throws Exception
	{
		String param=readParams(request);
		String oldKey=(String)request.getSession().getAttribute(Constant.Key);
		//解密
		String msg=EncryptAndDecipher.decipher2(oldKey, param);
		//解压缩
		String json=StringUtil.uncompressByGZIP(msg);
		
		return JSON.parseObject(json);
	}
	
	/**
	 * 设置返回信息
	 * lt@2013-9-5 下午03:40:16
	 * @param request
	 * @param msg
	 */
	public static void setResponseMsg(HttpServletRequest request,String msg) throws Exception
	{
		String oldKey=(String)request.getSession().getAttribute(Constant.Key);
		//生成新密钥
		String newKey=setNewKey(request);
		
		Cache.recordFlowInfo(3, (msg+newKey).length());
		//压缩
		msg=StringUtil.compressByGZIP(msg);
		//用旧密钥加密
		msg=EncryptAndDecipher.encrypt2(oldKey, msg);
		
		Cache.recordFlowInfo(4, (msg+newKey).length());
		//设置结果
		setResult(request,msg+newKey);
	}
	public static void setResponseMsg2(HttpServletRequest request,String msg) throws Exception
	{
		//压缩
		msg=StringUtil.compressByGZIP(msg);
		setResult(request, msg);
	}
	public static void setResult(HttpServletRequest request,String value)
	{
		//记录流量
		Cache.recordFlowInfo(1,value.length());
		request.setAttribute("result", value);
	}
	
	public static void removeKey(HttpServletRequest request)
	{
		request.getSession().removeAttribute(Constant.Key);
	}
	
}
